package com.lxyk.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxyk.yygh.listener.DataListener;
import com.lxyk.yygh.mapper.DictMapper;
import com.lxyk.yygh.model.cmn.Dict;
import com.lxyk.yygh.service.DictService;
import com.lxyk.yygh.vo.cmn.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * @Cacheable(value = "dict",keyGenerator = "keyGenerator") 适用于查询
     * 根据方法对其返回结果进行缓存，下次请求时，如果缓存存在，则直接读取缓存数据返回；
     * 如果缓存不存在，则执行方法，并把返回的结果存入缓存中。一般用在查询方法上。
     * @param id
     * @return
     */
    /**
     * 根据数据id查询子数据列表
     * @param id
     * @return
     * id=
     */
    //数据字典
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChild(Long id) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(dictQueryWrapper);
//        是否含有子节点
        for (Dict dict : dicts) {
            boolean b = hasChildren(dict.getId());
            if(b){
                dict.setHasChildren(true);
            }else{
                dict.setHasChildren(false);
            }
        }
        return dicts;
    }

    //判断是否有子节点
    public boolean hasChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer rel = baseMapper.selectCount(queryWrapper);
        return rel>0;
    }

    //导出数据字典
    @Override
    public void exportData(HttpServletResponse response){

        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            // FileName &#x6587;&#x4EF6;&#x540D;&#xFF0C;&#x8FD9;&#x91CC;&#x4F7F;&#x7528;&#x7684;&#x52A0;&#x5BC6;&#x6570;&#x636E;&#x5B57;&#x5178;
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");


            List<Dict> dicts = baseMapper.selectList(null);
            ArrayList<DictEeVo> list = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                list.add(dictEeVo);
            }
            //调用方法写，sheet(名字）
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(list);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     * @param dictService
     *   @CacheEvict(value = "dict", allEntries=true)
     *   使用该注解标志的方法，会清空指定的缓存。一般用在更新或者删除方法上
     */
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importData(MultipartFile file,DictService dictService) {

        try{
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DataListener(dictService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

   //获取数据字典名称，name属性
    @Override
    public String getDictName(String dictCode, String value) {
        //dict_code Province,Hostype,只有顶级父类才会有dict_code
        //说明这些的parent_id都是dict_code查询这个实体的id
        if(StringUtils.isEmpty(dictCode)){
            //根据value进行确认
            LambdaQueryWrapper<Dict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dictLambdaQueryWrapper.eq(Dict::getValue,value);
            Dict dict = baseMapper.selectOne(dictLambdaQueryWrapper);
            if(dict!=null){
                return dict.getName();//
            }
        }else{
             //如果dictCode不为空,根据dictCode和value查询
            //根据dictCode从新dict对象，得到dict的id值
            Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
            Long dictId = dict.getId();
            LambdaQueryWrapper<Dict>  lambdaQuery=new LambdaQueryWrapper<Dict>();
            lambdaQuery.eq(Dict::getParentId,dictId);
            lambdaQuery.eq(Dict::getValue,value);
            Dict finalDict = baseMapper.selectOne(lambdaQuery);
            return finalDict.getName();
        }
        return "";
    }

//    根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        Long id = dict.getId();
        //根据id获取子节点
        if(null == dict) return null;
        return this.findChild(dict.getId());
    }
}
